/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package NetworkSender;

import FrameWork.Item;
import NetworkPackage.clientConnection;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import javax.microedition.io.StreamConnection;

/**
 * the room is using this class to queue the outgoing messages 
 */
public class ResultScheduler {
    static ResultScheduler instance;
    boolean state;          // indicating if the class can handle a new item currently or not
    Queue<Item> queue;
    ResultScheduler() {
        queue = new ArrayBlockingQueue<Item>(100);
    }
    public static ResultScheduler getIntsance()
    {
        if(instance == null)
        {
            instance = new ResultScheduler();
        }
        return instance;
    }
    
    public void addItem(Item item)   // adding new item in the queue
    {
        queue.add(item); 
        _notify();
    }
    public Item deleteItem()        // retur the head of the queue and deleting it
    {
        if(queue.isEmpty())
           return null;     // error
        return queue.remove(); 
    }
    public boolean hasItems()       // indicating if the class can handle a new item currently or not
    {
        return (!queue.isEmpty());
    }
    public void _notify()           // this funcion uses the message sender to convert the message from item to xml format and encrypting it
    {
        MessageSender msgSdr = MessageSender.getInstance();
        int n = queue.size();
        for(int i = 0;i < n;i++)
        {
            Item item = queue.remove();       // remove the item
            if(clientConnection.list[item.getReceiverID()] != null)
            {   // if the connection exists
                item = msgSdr.encryptItem(item);
                StreamConnection strCon = clientConnection.list[item.getReceiverID()];
                String str = msgSdr.getXML(item);
                msgSdr.addItem(str,strCon);
            }
            else
            {   // add the item to the queue again if the connection is not available 
                queue.add(item);
            }
        }
    }
}
